package com.color.admin.common.core.base;

import org.springframework.data.domain.AuditorAware;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author HaiQiu
 * @date 2022/1/16
 * 系统配置基类
 */
public class BaseConfig implements WebMvcConfigurer, AuditorAware<String> {

    /**
     * 添加拦截器
     *
     * @param registry 拦截器注册
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        AuthInterceptor authInterceptor = new AuthInterceptor();
        registry.addInterceptor(authInterceptor);
    }


    /**
     * 实现AuditorAware类方法，jpa实现注解设置创建人，更新人
     *
     * @return
     */
    @Override
    public Optional<String> getCurrentAuditor() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (ObjectUtils.isEmpty(requestAttributes)){
            return Optional.empty();
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        if (ObjectUtils.isEmpty(request)) {
            return Optional.empty();
        }
        String username = (String) request.getAttribute(AuthInterceptor.USER_NAME);
        System.out.println("jpa实现注解设置创建人，更新人：" + username);
        if (username != null) {
            return Optional.of(username);
        }
        return Optional.empty();
    }
}
